// 定义卡片类型
const cardTypes = ['sheep1', 'sheep2', 'sheep3', 'grass1', 'grass2', 'flower1', 'flower2'];
const MAX_SLOT_COUNT = 7;
const START_Z_INDEX = 1000;
let gameCards = [];

// 音效定义
let clickSound, matchSounds;

try {
    clickSound = new Audio('assets/sounds/click.mp3');
    matchSounds = [
        new Audio('assets/sounds/match1.mp3'),
        new Audio('assets/sounds/match2.mp3')
    ];
    
    // 预加载音效
    clickSound.load();
    matchSounds.forEach(sound => sound.load());
} catch (e) {
    console.error('音效加载失败:', e);
    clickSound = { play: () => {} };
    matchSounds = Array(3).fill({ play: () => {} });
}

// 检查卡片覆盖状态
function checkCardOverlap(cards) {
    if (!cards || cards.length === 0) {
        console.log('没有卡片可检查是否被覆盖');
        return;
    }

    // 清除所有卡片的覆盖状态
    cards.forEach(card => {
        card.classList.remove('card-overlapped');
    });

    // 检查每个卡片是否被更高层级的卡片覆盖
    for (let i = 0; i < cards.length; i++) {
        const currentCard = cards[i];
        const currentRect = currentCard.getBoundingClientRect();
        
        const points = [
            {x: currentRect.left, y: currentRect.top},
            {x: currentRect.right, y: currentRect.top},
            {x: currentRect.left, y: currentRect.bottom},
            {x: currentRect.right, y: currentRect.bottom}
        ];
        
        let flag = false;
    
        for (const higherCard of cards.filter(card => card !== currentCard && card.style.zIndex >= currentCard.style.zIndex)) {
            const higherRect = higherCard.getBoundingClientRect();
            
            // 检查当前卡片的四个角点是否在更高层级卡片的矩形内
            for (const point of points) {
                if (point.x > higherRect.left && point.x < higherRect.right &&
                    point.y > higherRect.top && point.y < higherRect.bottom) {
                    flag = true;
                
                    break;
                }
            }
            
            if (flag) {
                break
            }
        }
        
        if (flag) {
            currentCard.classList.add('card-overlapped');
        } else {
            currentCard.classList.remove('card-overlapped');
            // console.log(`卡片 [${currentCard.style.zIndex}]${currentCard.className} 未被更高层级卡片覆盖`);
        }
    }
}

// 游戏状态
let score = 0;
let totalMoves = 0;
let selectedCards = [];

// DOM元素
const cardArea = document.getElementById('card-area');
const selectionArea = document.getElementById('selection-area');
const cardStack = document.getElementById('card-stack');
const scoreElement = document.getElementById('score');
const totalMovesElement = document.getElementById('total-moves');
const startBtn = document.getElementById('start-btn');
const resetBtn = document.getElementById('reset-btn');

// 生成卡片
function generateCards() {
    const cards = [];
    const CARD_COMB_NUM = 33;
    const cardsPerType = Math.floor(CARD_COMB_NUM / cardTypes.length);
    
    // 生成基础组合
    let cardCombinations = [];
    cardTypes.forEach(type => {
        for (let i = 0; i < cardsPerType; i++) {
            cardCombinations.push(type, type, type);
        }
    });
    
    // 补充剩余组合
    const remaining = CARD_COMB_NUM - (cardsPerType * cardTypes.length);
    for (let i = 0; i < remaining; i++) {
        const type = cardTypes[i % cardTypes.length];
        cardCombinations.push(type, type, type);
    }
    
    // 打乱顺序
    cardCombinations = cardCombinations.sort(() => Math.random() - 0.5);
    
    // 创建卡片
    for (let i = 0; i < cardCombinations.length; i++) {
        const card = document.createElement('div');
        const type = cardCombinations[i];
        card.className = `card ${type}`;
        card.style.backgroundImage = `url(assets/images/${type}.svg)`;
        card.style.backgroundSize = 'contain';
        card.style.backgroundRepeat = 'no-repeat';
        card.style.backgroundPosition = 'center';
        card.style.left = `${Math.random() * (cardArea.offsetWidth - 60)}px`;
        card.style.top = `${Math.random() * (cardArea.offsetHeight - 60)}px`;
        
        // 设置卡片z-index
        card.style.zIndex = START_Z_INDEX + i;
        card.addEventListener('click', () => handleCardClick(card));
        
        cardArea.appendChild(card);
        cards.push(card);
    }

    gameCards = cards;
    checkCardOverlap(gameCards);
}

// 处理卡片点击
let isClickLocked = false;

function handleCardClick(card) {
    if (isClickLocked) {
        console.log('点击被锁定，防止重复点击');
        return;
    }
    
    if (card.classList.contains('card-overlapped')) {
        console.log('卡片被更高层级卡片覆盖，无法点击');
        return;
    } else {
        console.log('卡片未被更高层级卡片覆盖，成功触发点击事件');
        if (!clickSound) {
            clickSound = new Audio('assets/sounds/click.mp3');
        }
        clickSound.currentTime = 0;
        clickSound.play();
    }
    
    isClickLocked = true;
    
    const type = card.className.split(' ')[1];
    console.log('选择的卡片类型:', type);
    
    // 创建新卡片元素
    const selectedCard = document.createElement('div');
    selectedCard.className = `card ${type}`;
    selectedCard.style.backgroundImage = `url(assets/images/${type}.svg)`;
    selectedCard.style.backgroundSize = 'contain';
    selectedCard.style.backgroundRepeat = 'no-repeat';
    selectedCard.style.backgroundPosition = 'center';
    
    // 设置初始位置为点击卡片的位置
    const cardRect = card.getBoundingClientRect();
    selectedCard.style.position = 'absolute';
    selectedCard.style.left = `${cardRect.left}px`;
    selectedCard.style.top = `${cardRect.top}px`;
    document.body.appendChild(selectedCard);
    
    // 计算目标位置
    const index = selectedCards.length;
    const row = Math.floor(index / MAX_SLOT_COUNT);
    const col = index % MAX_SLOT_COUNT;
    const targetLeft = col * 70 + 10;
    const targetTop = row * 70 + 10;
    
    // 添加移动动画
    selectedCard.style.transition = 'all 0.3s ease-out';
    
    // 计算中间点（屏幕底部）
    const midLeft = cardRect.left;
    const midTop = window.innerHeight - 100;
    
    // 第一阶段动画：向下移动到屏幕底部
    setTimeout(() => {
        selectedCard.style.left = `${midLeft}px`;
        selectedCard.style.top = `${midTop}px`;
        
        // 第二阶段动画：从底部移动到卡槽
        setTimeout(() => {
            selectedCard.style.left = `${targetLeft}px`;
            selectedCard.style.top = `${targetTop}px`;
            
            // 动画完成后添加到卡槽
            setTimeout(() => {
                document.querySelector('.card-stack-container').appendChild(selectedCard);
                selectedCard.dataset.index = selectedCards.length;
                selectedCards.push(type);
                
                // 移除原卡片
                card.remove();
                gameCards = gameCards.filter(c => c !== card);
                
                // 检查匹配
                const hasMatches = checkMatches();
                updateStats();
                checkCardOverlap(gameCards);
                
                // 如果超过上限且没有消除，结束游戏
                if (selectedCards.length > MAX_SLOT_COUNT && !hasMatches) {
                    console.warn('游戏结束条件触发');
                    alert('游戏结束！');
                }
                
                // 解锁点击
                isClickLocked = false;
            }, 300);
        }, 300);
    }, 10);
}

// 检查匹配
function checkMatches() {
    console.log('开始检查匹配');
    const counts = {};
    selectedCards.forEach(type => {
        counts[type] = (counts[type] || 0) + 1;
    });
    console.log('卡片计数:', counts);

    let hasMatches = false;
    for (const type in counts) {
        if (counts[type] >= 3) {
            console.log('发现匹配:', type, '数量:', counts[type]);
            // 移除匹配的卡片
            const indices = [];
            selectedCards.forEach((t, i) => {
                if (t === type) indices.push(i);
                if (indices.length === 3) return;
            });
            
            indices.sort((a, b) => b - a).forEach(i => {
                selectedCards.splice(i, 1);
                const cardToRemove = document.querySelector(`.card-stack-container .card[data-index="${i}"]`);
                if (cardToRemove) cardToRemove.remove();
            });
            
            score += 10;
            hasMatches = true;
            console.log('匹配成功，新得分:', score);
            // 随机播放一个消除音效
            const randomIndex = Math.floor(Math.random() * matchSounds.length);
            matchSounds[randomIndex].currentTime = 0;
            matchSounds[randomIndex].play();
            updateStats();
        }
    }
    
    // 重新排版剩余卡片
    if (hasMatches) {
        document.querySelector('.card-stack-container').innerHTML = '';
        selectedCards.forEach((type, i) => {
            const selectedCard = document.createElement('div');
            selectedCard.className = `card ${type}`;
            selectedCard.style.backgroundImage = `url(assets/images/${type}.svg)`;
            selectedCard.style.backgroundSize = 'contain';
            selectedCard.style.backgroundRepeat = 'no-repeat';
            selectedCard.style.backgroundPosition = 'center';
            selectedCard.dataset.index = i;
            
            const row = Math.floor(i / 4);
            const col = i % 4;
            selectedCard.style.position = 'absolute';
            selectedCard.style.left = `${col * 70 + 10}px`;
            selectedCard.style.top = `${row * 70 + 10}px`;
            
            document.querySelector('.card-stack-container').appendChild(selectedCard);
        });
    }
    
    if (selectedCards.length >= MAX_SLOT_COUNT) {
        console.warn('游戏结束条件触发');
        alert('游戏结束！');
    }
    console.log('匹配检查完成');
    return hasMatches;
}

// 更新状态显示
function updateStats() {
    totalMoves++;
    scoreElement.textContent = score;
    totalMovesElement.textContent = totalMoves;
    
    const count = selectedCards.length;
    updateCardStackStatus(count);
    
    if (gameCards.length <= 0) {
        alert(`游戏结束！最终得分: ${score}`);
    }
}

// 更新卡片栈状态显示
function updateCardStackStatus(count) {
  const cardStackInfo = document.querySelector('.card-stack-info');
  
  if ((7 - count) <= 3) {
    cardStackInfo.textContent = `卡槽: ${count}/${MAX_SLOT_COUNT}`;
    cardStackInfo.className = 'card-stack-info status-3';
  } else {
    cardStackInfo.textContent = `卡槽: ${count}/${MAX_SLOT_COUNT}`;
    cardStackInfo.className = 'card-stack-info status-abundant';
  }
}

// 初始化游戏
function initGame() {
    console.log('初始化游戏开始');
    cardArea.innerHTML = '';
    document.querySelector('.card-stack-container').innerHTML = '';
    score = 0;
    selectedCards = [];
    scoreElement.textContent = score;
    totalMovesElement.textContent = totalMoves;
    generateCards();
    console.log('初始化游戏完成');
}

// 事件监听
startBtn.addEventListener('click', initGame);
resetBtn.addEventListener('click', initGame);

// 开始游戏
initGame();